package cn.edu.ldh.toolapp.slice;

import cn.edu.ldh.toolapp.ResourceTable;
import cn.edu.ldh.toolapp.util.ImgUtil;
import cn.edu.ldh.toolapp.util.ToastUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.TextField;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.PixelMap;

public class JokeAbilitySlice extends AbilitySlice {

    private TextField qqTf;
    private Image qqImg;
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 1, "JokeAbilitySlice");
    private PixelMap pixelMap;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_joke);
        this.startInit();
    }

    //初始化组件
    private void startInit() {
        qqTf = (TextField) findComponentById(ResourceTable.Id_joke_qq_tf);
        //清空输入框
        qqTf.setText("");
        qqImg = (Image) findComponentById(ResourceTable.Id_joke_qq_img);
        findComponentById(ResourceTable.Id_joke_sub_btn).setClickedListener(this::getQQImg);
        findComponentById(ResourceTable.Id_joke_back_btn).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                terminate();
            }
        });
    }

    //获取QQ头像
    private void getQQImg(Component component) {
        String imgUrl = "https://q1.qlogo.cn/g?b=qq&nk=" + qqTf.getText() + "&s=100";
        //判断输入框是否为空
        if(qqTf.getText().equals("")) {
            ToastUtil.showToast(this, "不能为空");
            return;
        }
        //通过子线程获取头像
        TaskDispatcher taskDispatcher = createParallelTaskDispatcher("", TaskPriority.DEFAULT);
        taskDispatcher.syncDispatch(() -> {
            //生成位图
            pixelMap = ImgUtil.urlToPixelMap(imgUrl);
            getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
                @Override
                public void run() {
                    //圆形图片
                    qqImg.setCornerRadius(1000f);
                    //更新位图
                    qqImg.setPixelMap(pixelMap);
                }
            });
        });
        //给组件添加双击事件
        qqImg.setDoubleClickedListener(this::saveIMG);
        qqTf.setText("");
        ToastUtil.showToast(this, "生成成功");
    }

    //保存图片到相册
    private void saveIMG(Component component) {
        ImgUtil.saveImg(this, qqImg.getPixelMap());
        ToastUtil.showToast(this, "保存成功");
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
